package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 文章列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.参数校验
        if (null== dto && dto.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser user = WmThreadLocalUtil.get();
        if (null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.设置分页参数
        IPage<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        //3.设置查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        queryWrapper.eq(WmNews::getUserId,user.getId());
        if (null != dto.getStatus()){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if (null != dto.getChannelId()){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        if (null != dto.getBeginPubDate() && dto.getEndPubDate() != null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),
                    dto.getEndPubDate());
        }
        //4.查询数据
        super.page(page,queryWrapper);
        //5.封装结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     *
     *发布文章或保存草稿
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.参数校验
        if (null== dto ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser user = WmThreadLocalUtil.get();
        if (null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.保存或更新文章内容
        WmNews wmNews = saveOrUpdateNews(dto, user);
        //2.1如果是保存草稿则返回成功
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //2.2抽取内容中的所有图片
        List<String> urls = ectractUrlInfo(dto.getContent());
        //3.保存内容图片与素材之间的关系
        saveRelativeInfoForContent(urls,wmNews);
        //4.保存封面图片与素材之间的关系
        saveRelativeInfoForCover(urls,wmNews,dto);
        //5.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片与素材之间的关系
     * @param urls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> urls, WmNews wmNews, WmNewsDto dto) {
        //1.获取传递过来的封面图片
        List<String> images = dto.getImages();
        //1.1处理封面自动的情况
        if (dto.getType() == -1){
            if (null == urls || urls.size() == 0){
                wmNews.setType((short) 0);
            }else if (urls.size() < 3){
                wmNews.setType((short) 1);
                images=urls.stream().limit(1).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(images.toArray(),","));
            }else {
                wmNews.setType((short) 3);
                images=urls.stream().limit(3).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(images.toArray(),","));
            }
            //更新文章封面的类型
            super.updateById(wmNews);
        }
        //2.判断封面是否无图
        if (null != images && images.size()!= 0){
            saveRelativeInfo(images,wmNews, (short) 1);
        }

    }

    /**
     * 保存文章中图片与素材之间的关系
     * @param urls
     * @param wmNews
     */
    private void saveRelativeInfoForContent(List<String> urls, WmNews wmNews) {
        saveRelativeInfo(urls,wmNews, (short) 0);
    }

    /**
     * 抽取的方法
     * @param urls
     * @param wmNews
     * @param type
     */
    private void saveRelativeInfo(List<String> urls, WmNews wmNews,short type){
        //1.对urls进行去重处理
        urls=urls.stream().distinct().collect(Collectors.toList());
        //2.通过url地址查询素材id
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, urls));
        List<Integer> ids = wmMaterials.stream().map(item -> item.getId()).collect(Collectors.toList());
        //3.判断素材是否有被删除过
        if (null == ids && ids.size() != urls.size()){
            throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
        }
        //4.批量保存文章和素材之间的关系
        wmNewsMaterialMapper.saveRelations(ids,wmNews.getId(), type);
    }

    /**
     *从内容中提取图片
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> urls = new ArrayList<>();

        List<Map> list = JSONArray.parseArray(content, Map.class);
        //遍历获取所有数据返回
        for (Map map : list) {
            if (map.get("type").equals("image")){//根据前端参数判断
                urls.add(map.get("value").toString());//根据前端参数获取
            }
        }
        return urls;
    }

    /**
     * 保存或更新文章内容
     * @param dto
     * @param wmUser
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto, WmUser wmUser) {

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //处理图片
        String images = StringUtils.join(dto.getImages().toArray(), ",");
        wmNews.setImages(images);
        //设置参数
        wmNews.setUserId(wmUser.getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //处理自动-数据库使用了unsigned修饰不能存储负数
        if (dto.getType() == -1){
            wmNews.setType(null);
        }
        //1.新增
        if (null==dto.getId()){

            super.save(wmNews);
        }else {
            //修改
            //删除文章和素材之间的关系
            wmNewsMaterialMapper.delete(Wrappers
                    .<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,dto.getId()));

            super.updateById(wmNews);
        }
        return wmNews;
    }
}
